package com.zyh.demo.homework.test2;

import com.zyh.demo.homework.test2.domain.Student;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zyh
 * @Date 2024/8/14 19:17
 * @Description
 */

public class WriterXML {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student("08001", 32, "0800101", "赵明", "1985-12-23"));
        list.add(new Student("08002", 28, "0800201", "胡广飞", "1985-10-05"));

        XMLWriter xmlWriter = null;
        Document document = DocumentHelper.createDocument();
        try {
            //添加根节点
            Element rootElement = document.addElement("students");
            //子节点添加孙子节点
            //添加子节点
            Element student1 = rootElement.addElement("student1");
            Element classId1 = student1.addElement("classId");
            classId1.addText(list.get(0).getClassId());
            Element stuCount1 = student1.addElement("stuCount");
            stuCount1.addText(Integer.toString(list.get(0).getStuCount()));
            Element stuId1 = student1.addElement("stuId");
            stuId1.addText(list.get(0).getStuId());
            Element name1 = student1.addElement("name");
            name1.addText(list.get(0).getName());
            Element birth1 = student1.addElement("birth");
            birth1.addText(list.get(0).getBirth());

            //添加子节点
            Element student2 = rootElement.addElement("student2");
            //子节点添加孙子节点
            Element classId2 = student2.addElement("classId");
            classId2.addText(list.get(1).getClassId());
            Element stuCount2 = student2.addElement("stuCount");
            stuCount2.addText(Integer.toString(list.get(1).getStuCount()));
            Element stuId2 = student2.addElement("stuId");
            stuId2.addText(list.get(1).getStuId());
            Element name2 = student2.addElement("name");
            name2.addText(list.get(1).getName());
            Element birth2 = student2.addElement("birth");
            birth2.addText(list.get(1).getBirth());

            //添加完成后创建模板
            OutputFormat prettyPrint = OutputFormat.createPrettyPrint();
            //指定编码
            prettyPrint.setEncoding("UTF-8");
            xmlWriter = new XMLWriter(new FileWriter("D:\\Code\\IDEA\\idea_projects\\JavaSE-plus\\day16-code\\src\\com\\zyh\\demo\\homework\\test2\\Student.xml"), prettyPrint);
            xmlWriter.write(document);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关流
                xmlWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
